package cn.rongdao.jrkabao.ui.information;

import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.information.CardByToolsBean;
import cn.rongdao.jrkabao.bean.information.InfoCardBean;
import cn.rongdao.jrkabao.bean.takephoto.ValidateIDCardInfoBean;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.information.AddCardInfoModel;
import cn.rongdao.jrkabao.model.information.CardInfoByCardNumberModel;
import cn.rongdao.jrkabao.model.information.GetCardInfoModel;
import cn.rongdao.jrkabao.model.takephoto.IdCardNameAndNumberModel;
import cn.rongdao.jrkabao.util.listener.OnTextChangeListener;
import cn.rongdao.jrkabao.util.phone.PhoneUtil;
import cn.rongdao.jrkabao.widget.CardEditText;

/**
 * Created by jiangyongxing on 2016/8/25.
 * 描述：添加储蓄卡的界面
 */
public class AddCardActivity extends BaseAutoFinishActivity implements View.OnClickListener {

    private TitleBarUIComponent titleBarUIComponent;
    private TextView mName;
    private TextView indentificationCard;
    private CardEditText number;
    private Button submit;
    private EditText phone;
    private String numberStr;
    private String phoneStr;
    private String bankName = "";
    private Map<String, String> mMap;


    @Override
    protected int layoutRes() {
        return R.layout.activity_add_card;
    }

    @Override
    protected void initView() {
        super.initView();
        initData();
        titleBarUIComponent = (TitleBarUIComponent) findViewById(R.id.aaic_titlebar);
        initTitleBar();
        mName = (TextView) findViewById(R.id.activity_add_card_name);
        indentificationCard = (TextView) findViewById(R.id.activity_add_card_indentification_card);
        number = (CardEditText) findViewById(R.id.activity_add_card_number);
        phone = (EditText) findViewById(R.id.activity_add_card_phone);
        submit = (Button) findViewById(R.id.activity_add_card_submit);
        submit.setOnClickListener(this);
        number.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!FRString.isEmpty(number.getContextText().trim())) {
                    if (number.getContextText().trim().length() == 16) {
                        requestCardInfo();
                    }
                }
            }
        });

    }

    private void initTitleBar() {
        titleBarUIComponent.initTitleBlack("添加储蓄卡");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        titleBarUIComponent.setBottomViewVisiable(true);
        titleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    protected void initData() {
        String mUserId = UserDao.getInstance().getUserId();
        String mToken = UserDao.getInstance().getToken();
        mMap = new HashMap<>();
        mMap.put("uid", mUserId);
        mMap.put("user_id", mUserId);
        mMap.put("token", mToken);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getIndentificationInfo();
        getCardNumber();
    }

    /**
     * 根据银行卡号获取银行卡信息
     */
    private void requestCardInfo() {
        if (checkData(false)) {
            CardInfoByCardNumberModel.getInstance().execute(numberStr, new FRBaseObserver<CardByToolsBean>(this) {
                @Override
                protected void onBaseNext(CardByToolsBean data) {
                    bankName = data.getBankname();
                    submit.setEnabled(true);
                }

                @Override
                protected void onBaseError(Throwable t) {
                    super.onBaseError(t);
                    FRToast.showToastSafe("请检查卡号是否有误");
                    submit.setEnabled(false);
                }
            });
        }
    }

    /**
     * 获取储蓄卡信息 用户已经填写过的
     */
    private void getCardNumber() {
        GetCardInfoModel.getInstance().execute(mMap, new FRBaseObserver<List<InfoCardBean>>(this) {
            @Override
            protected void onBaseNext(List<InfoCardBean> data) {
                if (!TextUtils.isEmpty(data.get(0).getCard_no()) && !TextUtils.isEmpty(data.get(0).getTel())) {
                    number.setFocusable(false);
                    phone.setFocusable(false);
                    submit.setEnabled(false);
                    submit.setVisibility(View.GONE);
                } else {
                    submit.setEnabled(true);
                    submit.setVisibility(View.VISIBLE);
                }
                number.setText(data.get(0).getCard_no());
                number.setSelection(number.getContextText().trim().length());
                phone.setText(data.get(0).getTel());
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        submit.setVisibility(View.VISIBLE);
                    }
                });
            }
        });
    }

    /**
     * 获取身份信息
     */
    private void getIndentificationInfo() {
        IdCardNameAndNumberModel.getInstance().execute(new FRBaseObserver<ValidateIDCardInfoBean>(this, "正在加载") {
            @Override
            protected void onBaseNext(ValidateIDCardInfoBean data) {
                if (!TextUtils.isEmpty(data.getIdentity_num()) && !TextUtils.isEmpty(data.getReal_name())) {
                    mName.setText(data.getReal_name());
                    indentificationCard.setText(data.getIdentity_num());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_add_card_submit:
                if (checkData(true)) {
                    mMap.put("card_no", numberStr);
                    mMap.put("tel", phoneStr);
                    mMap.put("bank", bankName);
                    AddCardInfoModel.getInstance().execute(mMap, new FRBaseObserver<String>(this, "正在提交") {
                        @Override
                        protected void onBaseNext(String data) {
                            FRToast.showToastSafe("提交成功");
                            finish();
                        }
                    });
                }
                break;
        }
    }

    private boolean checkData(boolean isSubmit) {

        numberStr = number.getContextText().trim();
        phoneStr = phone.getText().toString().trim();
        if (numberStr == null || "".equals(numberStr)) {
            FRToast.showToastSafe("储蓄卡号不能为空");
            return false;
        }
        if (numberStr.length() > 19 || numberStr.length() < 15) {
            FRToast.showToastSafe("储蓄卡号格式不正确");
            return false;
        }
        if (isSubmit)
            if (!PhoneUtil.validataPhone(phoneStr)) {
                return false;
            }
        return true;
    }
}